// Starfield
// Scroll the mouse wheel or press the arrow keys to travel through the cosmos
import pulpcore.Input;
import pulpcore.Stage;
import pulpcore.image.BlendMode;
import pulpcore.math.CoreMath;
import pulpcore.sprite.Group;
import pulpcore.sprite.ImageSprite;

public class StarField extends Group
{

	int numStarImages = 3;
	int numStars = 25;
	int zoomX;
	int zoomY;
	double zoomSpeed;

	public StarField()
	{
		super(0, 0, Stage.getWidth(), Stage.getHeight());

		for (int i = 0; i < numStars; i++)
		{
			int r = CoreMath.rand(numStarImages - 1);
			Star s = new Star(this, "star" + r + ".png");
			s.visible.set(false);
			add(s);
		}
	}

	@Override
	public void update(int elapsedTime)
	{
		super.update(elapsedTime);
		zoom((int)width.get()/2,(int)height.get()/2,-0.1f);
	}

	void zoom(int x, int y, double speed)
	{
		zoomX = x;
		zoomY = y;
		zoomSpeed = speed;
	}

	class Star extends ImageSprite
	{

		double z;
		StarField sf;

		public Star(StarField sf, String image)
		{
			super(image, CoreMath.rand(0, sf.width.get()), CoreMath.rand(0, sf.height.get()));
			this.sf = sf;
			setZ(CoreMath.rand(1.0, 4.0));
			setBlendMode(BlendMode.Add());
		}

		@Override
		public void update(int elapsedTime)
		{
			super.update(elapsedTime);

			double speed = zoomSpeed * z * z / 3000;
			double dx = (x.get() - zoomX) * elapsedTime * speed;
			double dy = (y.get() - zoomY) * elapsedTime * speed;
			setZ(z + elapsedTime * speed);
			setLocation(x.get() + dx, y.get() + dy);

			if (x.get() < 0 || x.get() >= sf.width.get() || y.get() < 0 || y.get() >= sf.height.get())
			{
				visible.set(true);
				setZ(CoreMath.rand(1, 3.0));
				setLocation(zoomX + CoreMath.rand(-sf.width.get() / 10, sf.width.get() / 10), zoomY
						+ CoreMath.rand(-sf.height.get() / 10, sf.height.get() / 10));
			} else if (alpha.get() < 50)
			{
				visible.set(true);
				setZ(CoreMath.rand(2,4));
				setLocation(zoomX + CoreMath.rand(-sf.width.get() / 2, sf.width.get() / 2), zoomY
					+ CoreMath.rand(-sf.height.get() / 2, sf.height.get() / 2));
			}
		}

		void setZ(double z)
		{
			this.z = z;
			setSize(z * 5, z * 5);
			alpha.animateTo(z >= 2 ? 255 : (int) (255 * (z - 1)),200);
		}
	}

}
